// 路由
import { createRouter, createWebHashHistory } from 'vue-router'
import { ACCESS_TOKEN, ROLE, MENUS } from '../config/constants';

// 引入组件
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Layout from '../views/Layout.vue'
import Login from '../views/Login.vue'

// 路由配置
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: Login },
    {
      path: '/layout', name: 'Layout', component: Layout, children: [
        { path: '/home', name: 'Home', component: Home, meta: { btnPermissions: ['admin', 'visitor'] } },
        { path: '/about', name: 'About', component: About, meta: { Permissions: ['admin'] } }
      ]
    }
  ]
})

// 路由权限
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {   // 登录页面清除缓存信息
    localStorage.removeItem(ACCESS_TOKEN);
    localStorage.removeItem(ROLE);
    localStorage.removeItem(MENUS);
  }
  // 当前没有token时且非login页面，则跳转到login,否则正常跳转
  let token = localStorage.getItem(ACCESS_TOKEN);
  if (!token && to.path != '/login') {
    next({ path: '/login' });
  } else {
    next();
  }
})

export default router;